/**
 * 入参
 * 存款类型（枚举数据源）typeList
 * 存款总行（枚举数据源） headBankList
 * 存款详情 depositInfo
 * state：1-指令下达（初始或通过持仓回填）    2-新增簿记（初始或通过持仓回填）    3-编辑簿记    4-簿记交收    5-簿记详情    6-指令详情
 * 出参
 * 响应组合变更事件，抛出组合ID
 * 通过onRef调用getInfo方法，获取当前存入指令的全部数据
 */
import React, { PureComponent } from 'react';
import {
  FormGroup,
  DATA_ENTRY,
  SeriesProductGroupC,
  InputNumberC,
  InputC,
  SingleDateC,
  AdvancedSearch,
  ProductGroupSepC,
  SelectC,
  NoQueryC,
  TableC,
  FirstHeaderC,
  SecondHeaderC,
} from '../../../comps';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Row, Col, Input, Modal } from 'antd';
import config from './config';
import investmentTypeData from '../../../utils/enumeratedValues/investmentType';
import { calculateFee } from '../../../utils/commonFunc';
const confirm = Modal.confirm;
import { connect } from 'dva';
import 'moment/locale/zh-cn';
import moment from 'moment';
const { TextArea } = Input;
const FormItem = Form.Item;

@connect(({ depositOrderM, userM: user, globalM, loading }) => ({
  depositOrderM,
  user,
  globalM,
  loading,
}))
@Form.create()
export default class WithdrawnOrder extends PureComponent {
  static defaultProps = {
    onRef: () => {},
  };
  state = {
    depositInfo: undefined, //存款详情
    typeList: [], //存款类型
    branchBankList: [], //存款分行
    accountList: [], //存款账户
    type: undefined, //当前指令的类型 1-指令下达（初始或通过持仓回填）    2-新增簿记（初始或通过持仓回填）    3-编辑簿记    4-簿记交收    5-簿记详情    6-指令详情
    feeData: {
      //费用自动计算条件
      productId: undefined,
      portfolioid: undefined,
      sectype: 'ck',
      orderside: 'i',
    },
  };
  componentDidMount() {
    this.props.onRef(this);
    this.setState({
      type: this.props.state,
    });
  }
  UNSAFE_componentWillReceiveProps(nextProps) {
    //存款详情默认是undefined，当存款详情变更时，更新初始化值；
    if (nextProps.depositInfo && nextProps.depositInfo !== this.state.depositInfo) {
      this.setState(
        {
          depositInfo: nextProps.depositInfo,
        },
        () => {
          this.setValues();
        },
      );
    }
  }

  //费用自动计算
  changeFee = (type, data) => {
    const {
      form: { setFieldsValue },
    } = this.formContent.props;
    if (this.props.type == 3 || this.props.type == 5) return; //详情不计算
    setTimeout(() => {
      if (data == undefined) {
        setFieldsValue({ fee: undefined });
        if (type == 'productId') {
          this.setState({ feeData: { ...this.state.feeData, productId: undefined, portfolioid: undefined } });
        } else {
          this.setState({ feeData: { ...this.state.feeData, [type]: undefined } });
        }
      } else {
        if (type == 'tradingCode') {
          this.setState({ feeData: { ...this.state.feeData, tradingCode: data.tradingCode, exchangecode: data.exchangeCode } }, () => {
            let fee = calculateFee(this.state.feeData, this.state.type == 10 ? true : false);
            fee.then((r) => {
              setFieldsValue({ fee: r });
            });
          });
        } else {
          this.setState({ feeData: { ...this.state.feeData, [type]: data } }, () => {
            let fee = calculateFee(this.state.feeData, this.state.type == 10 ? true : false);
            fee.then((r) => {
              setFieldsValue({ fee: r });
            });
          });
        }
      }
    }, 100);
  };

  //reset 重置
  reset = () => {
    this.setState({
      depositInfo: undefined, //存款详情
      typeList: [], //存款类型
      branchBankList: [], //存款分行
    });
    this.formContent.props.form.resetFields();
    this.formContent.props.form.setFieldsValue({
      combCode: undefined,
      fundCode: undefined,
    });
  };
  //回填详情信息
  setValues = () => {
    const { depositInfo, type } = this.state;
    const bankHead = depositInfo.bankHeadOfficeId ? depositInfo.bankHeadOfficeId : depositInfo.bankHeadOfficeName;
    if (this.state.type != 10) {
      //交易录入不参与
      //获取总行的下拉列表
      this.getHeadBankList(bankHead);
      this.getAccountInfo(bankHead);
    }
    this.formContent.props.form.setFieldsValue({
      // remark:depositInfo.remark,
      depositType: depositInfo.depositType,
      bankHeadOfficeName: this.state.type != 10 ? bankHead : depositInfo.bankHeadOfficeName,
      bankBranchName: depositInfo.bankBranchName,
      bankDepositBalance: depositInfo.bankDepositBalance,
      advanceInterestrate: depositInfo.advanceInterestrate,
      bankDrawDownBalance: depositInfo.bankDrawDownBalance,
      earlyDrawdownDate: moment(depositInfo.earlyDrawdownDate),
      withdrawnInterest: depositInfo.withdrawnInterest,
      account: depositInfo.account,
      investmentType: depositInfo.investmentType,
      fee: depositInfo.fee,
      jixiBase: depositInfo.jixiBase,
      secucodeName: depositInfo.secucodeName,
      secucodeType: depositInfo.secucodeType,
    });
    this.changeFee('price', depositInfo.bankDepositBalance);

    if (type > 2) {
      if (type == 10) return;
      this.formContent.props.form.setFieldsValue({
        remark: depositInfo.remark,
      });
    }
    if (depositInfo.userId && type > 2) {
      if (type == 10) return;
      this.formContent.props.form.setFieldsValue({
        orderPerson: depositInfo.userId + '-' + depositInfo.userName,
      });
    }
  };

  //组合改变
  groupOnChange = (value) => {
    //组合切换 清除掉数据
    this.formContent.props.form.setFieldsValue({
      depositType: undefined,
      bankHeadOfficeName: undefined,
      bankBranchName: undefined,
      bankDepositBalance: undefined,
      advanceInterestrate: undefined,
      bankDrawDownBalance: undefined,
      earlyDrawdownDate: moment(),
      withdrawnInterest: undefined,
    });
    this.changeFee('price', undefined);

    //抛出组合id
    if (value) this.props.getFundCode(value.key);
  };
  //查询总行列表
  getHeadBankList = (value) => {
    this.props.dispatch({
      type: 'depositOrderM/getHeadBankList',
      payload: {
        productId: this.props.depositInfo.combCode,
        value: value ? value : '',
      },
      callback: (type, value, data) => {
        if (type == 'success') {
          this.setState({
            headBankList: data || [],
          });
          this.props.vcBankName(data);
        } else {
          this.setState({
            headBankList: [],
          });
        }
      },
    });
  };
  //产品改变
  productOnChange = (value) => {
    //抛出产品id
    if (value) this.props.getProductCode(value.key);
  };
  //支取本金修改 计算支取利息
  balanceChnge = (e) => {
    this.formContent.props.form.setFieldsValue({
      bankDrawDownBalance: e,
    });
    this.calc(); //计算支取利息
  };
  calc = () => {
    //计算支取利息
    const { depositInfo } = this.state;
    if (depositInfo && depositInfo.advanceInterestrate && this.formContent.props.form.getFieldsValue().earlyDrawdownDate) {
      let rate = depositInfo.advanceInterestrate;
      let date = this.formContent.props.form.getFieldsValue().earlyDrawdownDate;
      let day = date.diff(moment(depositInfo.bankStartDate), 'day');
      let balance = this.formContent.props.form.getFieldsValue().bankDrawDownBalance;
      const val = balance && day !== 0 ? ((parseFloat((balance * rate) / 100) * day) / 365).toFixed(2) * 1 : undefined;
      this.formContent.props.form.setFieldsValue({
        withdrawnInterest: val,
      });
    }
  };
  //支取日变更 计算利息
  dateChange = (e) => {
    this.formContent.props.form.setFieldsValue({
      earlyDrawdownDate: e,
    });
    this.calc(); //计算支取利息
  };
  //根据分行查询存款账户
  getAccountInfo = (bankHead) => {
    const { depositInfo } = this.props;
    this.props.dispatch({
      type: 'depositOrderM/getAccountInfo',
      payload: {
        branchBankName: depositInfo.bankBranchName,
        bankNo: bankHead,
        accountType: depositInfo.depositType,
        productId: depositInfo.combCode,
      },
      callback: (type, data) => {
        if (type == 'success') {
          this.setState({
            accountList: data,
          });
        } else {
          this.setState({
            accountList: [],
          });
        }
      },
    });
  };
  formRender1 = () => {
    const {
      typeList,
      user: { currentUser },
      form: { getFieldDecorator },
    } = this.props;
    const { type, branchBankList, depositInfo, headBankList = [], accountList } = this.state;
    const {
      globalM: {
        dataDictionary: { JXJC = [], CKLX = [], BDLX = [] },
      },
    } = this.props;
    let disabled;
    if (type == 3 || type == 4 || type == 5 || type == 6) {
      disabled = true;
    }
    if (type == 1 || type == 2 || type == 10 || type == 11) {
      disabled = false;
    }
    let initData = depositInfo && depositInfo.combCode ? [depositInfo.combCode, depositInfo.fundCode] : undefined;
    var propsRef = this.formContent ? this.formContent.props : this.props;
    let depositType = propsRef.form.getFieldsValue().depositType;
    let type10 = [
      {
        type: DATA_ENTRY.SERIESPRODUCTGROUP,
        title: '系列产品',
        dataIndex: 'combCode',
        initialValue: this.props.listId,
        onChange: (e) => this.props.getFundCode(e ? e.value : undefined),
        disabled: true,
        rules: [{ required: true, message: '请选择系列产品!' }],
        span: 12,
        controlLabelSpan: 8,
      },
      {
        title: '存款类型',
        dataIndex: 'depositType',
        type: DATA_ENTRY.SELECT,
        dataSource: CKLX.map((item) => {
          return { value: item.code, title: item.value };
        }).filter((item) => item.code != '02'), //交易录入不需要通知类型
        isMultiple: false,
        optionTitle: true,
        disabled: true,
        initialValue: '01',
        rules: [{ required: true, message: '请选择存款类型!' }],
        span: 6,
        controlLabelSpan: 8,
      },
      {
        type: DATA_ENTRY.SELECT,
        title: '标的类别', // 显示名称
        dataIndex: 'secucodeType', // Form识别的Item ID
        dataSource: BDLX.map((item) => {
          return { value: item.code, title: item.value };
        }),
        isMultiple: false,
        disabled: true,
        rules: [{ required: depositType == '06' ? true : false, message: '请选择标的类别!' }],
        span: 6,
        controlLabelSpan: 8,
      },
      {
        type: DATA_ENTRY.INPUT,
        title: '标的名称', // 显示名称
        dataIndex: 'secucodeName', // Form识别的Item ID
        disabled: true,
        placeholder: '证券名称_证券代码',
        rules: [{ required: depositType == '06' ? true : false, message: '请输入标的名称!' }],
        span: 6,
        controlLabelSpan: 8,
      },
      {
        title: '存款总行',
        dataIndex: 'bankHeadOfficeName',
        type: DATA_ENTRY.INPUT,
        disabled: true,
        rules: [{ required: true, message: '请输入存款总行!' }],
        placeholder: '请输入',
        span: 6,
        controlLabelSpan: 8,
      },
      {
        title: '存款分行', // 显示名称
        dataIndex: 'bankBranchName', // Form识别的Item ID
        disabled: true,
        type: DATA_ENTRY.INPUT,
        rules: [{ required: true, message: '请输入存款分行!' }],
        span: 6,
        controlLabelSpan: 8,
      },
      {
        title: '存款账户',
        type: DATA_ENTRY.INPUT,
        dataIndex: 'account', // Form识别的Item ID
        disabled: true,
        rules: [{ required: true, message: '请输入存款账户!' }],
        span: 6,
        controlLabelSpan: 8,
      },
    ];
    let typeOther = [
      {
        type: DATA_ENTRY.PRODUCTGROUPSEP,
        disabled: disabled,
        title: ['产品', '组合'],
        initialValue: initData,
        authority: 'write',
        multipleGroup: false,
        dataIndex: ['combCode', 'fundCode'],
        rules: [[{ required: true, message: '请选择产品' }], [{ required: true, message: '请选择组合' }]],
        groupOnChange: (e) => {
          this.groupOnChange(e);
          this.changeFee('portfolioid', e?.key);
          this.props.portfolioCode(e ? e.info.portfolioCode : undefined); //向外抛出组合code
        },
        productOnChange: (e) => {
          this.productOnChange(e);
          this.changeFee('productId', e?.key);
          this.props.productCode(e ? e.info.portfolioCode : undefined); //向外抛出产品code
        },
        allowClear: false,
        exist: 1,
        span: 12,
        controlLabelSpan: 8,
        tradeModel: type == 1 || type == 2 ? ['BOOKKEEPING_MODE', 'COMMAND_MODE'] : undefined, //不包含估值解析和估值对接的产品
      },
      {
        type: DATA_ENTRY.SELECT,
        title: '投资类型',
        dataIndex: 'investmentType',
        initialValue: 'AC',
        disabled: true,
        dataSource: investmentTypeData,
        allowClear: true,
        rules: [{ required: false, message: '请选择' }],
        span: 6,
        controlLabelSpan: 8,
      },
      {
        type: DATA_ENTRY.SELECT,
        title: '存款类型', // 显示名称
        dataIndex: 'depositType', // Form识别的Item ID
        dataSource: CKLX.map((item) => {
          return { value: item.code, title: item.value };
        }),
        isMultiple: false,
        optionTitle: true,
        disabled: true,
        initialValue: '01',
        rules: [{ required: true, message: '请选择存款类型!' }],
        span: 6,
        controlLabelSpan: 8,
      },
      {
        type: DATA_ENTRY.SELECT,
        title: '标的类别', // 显示名称
        dataIndex: 'secucodeType', // Form识别的Item ID
        dataSource: BDLX.map((item) => {
          return { value: item.code, title: item.value };
        }),
        isMultiple: false,
        disabled: true,
        rules: [{ required: depositType == '06' ? true : false, message: '请选择标的类别!' }],
        span: 6,
        controlLabelSpan: 8,
      },
      {
        type: DATA_ENTRY.INPUT,
        title: '标的名称', // 显示名称
        dataIndex: 'secucodeName', // Form识别的Item ID
        disabled: true,
        placeholder: '证券名称_证券代码',
        rules: [{ required: depositType == '06' ? true : false, message: '请输入标的名称!' }],
        span: 6,
        controlLabelSpan: 8,
      },
      {
        title: '存款总行', // 显示名称
        dataIndex: 'bankHeadOfficeName', // Form识别的Item ID
        type: DATA_ENTRY.SELECT,
        dataSource: headBankList.map((item) => {
          return { value: item.bankNo, title: item.bankName };
        }),
        isMultiple: false,
        optionTitle: true,
        disabled: true,
        showSearch: true,
        filterOption: false,
        rules: [{ required: true, message: '请选择存款总行!' }],
        allowClear: true,
        span: 6,
        controlLabelSpan: 8,
      },
      {
        title: '存款分行', // 显示名称
        type: DATA_ENTRY.SELECT,
        dataIndex: 'bankBranchName', // Form识别的Item ID
        dataSource:
          branchBankList &&
          branchBankList.map((item) => {
            return { value: item.branchBankName, title: item.branchBankName };
          }),
        isMultiple: false,
        optionTitle: true,
        showSearch: true,
        onChange: this.bankBranchChange,
        filterOption: (input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0,
        disabled: true,
        rules: [{ required: true, message: '请选择存款分行!' }],
        span: 6,
        controlLabelSpan: 8,
      },
      {
        title: '存款账户',
        type: DATA_ENTRY.SELECT, // 显示名称
        dataIndex: 'account', // Form识别的Item ID
        dataSource:
          accountList &&
          accountList.map((item) => {
            return { value: item.value, title: item.value + '-' + item.title };
          }),
        isMultiple: false,
        optionTitle: true,
        showSearch: true,
        filterOption: (input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0,
        disabled: true,
        rules: [{ required: true, message: '请选择存款账户!' }],
        span: 6,
        controlLabelSpan: 8,
      },
    ];

    let commonData = [
      {
        type: DATA_ENTRY.INPUTNUMBER,
        dataIndex: 'bankDepositBalance',
        title: '存款金额',
        unit: '元',
        splitStyle: true,
        rules: [{ required: true, message: '请输入存款金额!' }],
        precision: 2,
        disabled: true,
        span: 6,
        controlLabelSpan: 8,
      },
      {
        type: DATA_ENTRY.INPUTNUMBER,
        dataIndex: 'bankDrawDownBalance',
        title: '支取本金',
        unit: '元',
        min: 0.01,
        splitStyle: true,
        rules: [{ required: true, message: '请输入支取本金!' }],
        precision: 2,
        disabled: type > 3 ? disabled : false,
        onChange: this.balanceChnge,
        span: 6,
        controlLabelSpan: 8,
      },
      {
        type: DATA_ENTRY.INPUTNUMBER,
        dataIndex: 'withdrawnInterest',
        title: '支取利息',
        unit: '元',
        min: 0.01,
        splitStyle: false,
        rules: [{ required: true, message: '请输入支取利息!' }],
        precision: 2,
        disabled: type > 3 ? disabled : false,
        span: 6,
        controlLabelSpan: 8,
      },
      {
        type: DATA_ENTRY.INPUTNUMBER,
        dataIndex: 'advanceInterestrate',
        title: '提前支取利率',
        unit: '%',
        min: 0,
        splitStyle: false,
        precision: 2,
        disabled: true,
        span: 6,
        controlLabelSpan: 8,
      },
      {
        type: DATA_ENTRY.SINGLEDATE,
        title: '支取日', // 显示名称
        dataIndex: 'earlyDrawdownDate', // Form识别的Item ID
        disableBegin: moment().subtract(1, 'days'),
        disableEnd: moment('2999-12-31'),
        onChange: this.dateChange,
        disabled: type > 3 ? disabled : false,
        rules: [{ required: true, message: '请选择支取日!' }],
        span: 6,
        controlLabelSpan: 8,
      },
      {
        type: DATA_ENTRY.SELECT,
        title: '计息基础', // 显示名称
        dataIndex: 'jixiBase', // Form识别的Item ID
        dataSource: JXJC.map((item) => {
          return { value: item.code, title: item.value };
        }),
        isMultiple: false,
        disabled: true,
        rules: [{ required: true, message: '请选择计息基础!' }],
        span: 6,
        controlLabelSpan: 8,
      },
      {
        type: DATA_ENTRY.INPUT,
        title: '下达人', // 显示名称
        dataIndex: 'orderPerson', // Form识别的Item ID
        initialValue: currentUser.userId + '-' + currentUser.name,
        disabled: true,
        rules: [{ required: true }],
        span: 6,
        controlLabelSpan: 8,
      },
      {
        title: '费用',
        dataIndex: 'fee',
        placeholder: '请输入',
        type: DATA_ENTRY.INPUTNUMBER,
        min: 0,
        precision: 2,
        splitStyle: true,
        disabled: type > 3 ? disabled : false,
        unit: '元',
        span: 6,
        controlLabelSpan: 8,
        hide: type == 10 ? false : true,
      },
      {
        dataIndex: 'remark',
        title: '备注',
        type: DATA_ENTRY.INPUT,
        disabled: type > 3 ? disabled : false,
        showTextArea: true,
        autosize: { minRows: 2, maxRows: 2 },
        span: 24,
        controlLabelSpan: 2,
      },
    ];
    let dataSource = [];
    if (type != 10) {
      dataSource = typeOther.concat(commonData);
    } else {
      dataSource = type10.concat(commonData);
    }
    return <FormGroup onRef={(ref) => (this.formContent = ref)} rowNumber={4} autoLayout={false} dataSource={dataSource} style={{ background: '#FAFBFC' }} />;
  };
  render() {
    return <div className={'saveOrder'}>{this.formRender1()}</div>;
  }
}
